<?php

require_once('Myzen/Oauth/Datastore/Interface.php');

class Myzen_Oauth_Datastore_Db implements Myzen_Oauth_Datastore_Interface {

	/* definition of the nonce table */
	protected $_dbNonceTableName = 'nonce';
	static protected $_dbNonceConsumerKeyCol = 'consumerKey';
	static protected $_dbNonceNonceCol = 'nonce';
	static protected $_dbNonceTimestampCol = 'timestamp';

	static protected $_nounceLifeTime = 300;
  
    
  public function lookup_consumer($consumerKey) {
    
    try{
    	$consumer = new Myzen_Oauth_consumer($consumerKey);	
    } catch(Myzen_Oauth_Exception $e) {
    	return;	
    }
    return $consumer;
     
  }
  
  
  public function getConsumerFromToken($token_type, $token) {

    $token = $this->lookup_token(null, $token_type, $token);
    if(!is_object($token)) throw new Myzen_Oauth_Exception('token not found');
  	$consumerKey = $token->getConsumerKey();
  	return $this->lookup_consumer($consumerKey);
  	
  }

  public function lookup_token($consumer, $tokenType, $tokenKey) {
     try{
       $token = Myzen_Oauth_Token::getToken($tokenType,$tokenKey);
     } catch(Myzen_Oauth_Token_Exception $e) {
     	return null;
     }
     
     return $token;
    
  }

  public function lookup_nonce($consumer, $token, $nonce, $timestamp) {
    
    $consumerKey = $consumer->key;
    
    $db = Zend_Registry::get('dt_dbs')->getDb('auth','nonce',$consumerKey);
  	
    $select = $db->select()->from($this->_dbNonceTableName);
    

    $select->where($db->quoteInto(self::$_dbNonceConsumerKeyCol ." = ?", $consumerKey));
    $select->where($db->quoteInto(self::$_dbNonceNonceCol ." = ?", $nonce));
    $select->where($db->quoteInto(self::$_dbNonceTimestampCol." >= ?",$timestamp - self::$_nounceLifeTime));

    $res = $db->fetchAll($select->__toString());   
    if(!empty($res)) return $nonce;
    
    $data = array(
    	self::$_dbNonceConsumerKeyCol => $consumerKey,
    	self::$_dbNonceNonceCol => $nonce,
    	self::$_dbNonceTimestampCol => time()
    );
    $db->insert($this->_dbNonceTableName, $data);
        
     return NULL;  	
  }
  
  
  public function cleanup_nounce() {
    $dbs = Zend_Registry::get('dt_dbs')->getAllDbs('auth','nonce');
    $nbNounces = 0;
    $minTime = time() - self::$_nounceLifeTime;
    foreach($dbs as $num => $db) {
    	$nbNounces += $db->delete($this->_dbNonceTableName,$db->quoteInto(self::$_dbNonceTimestampCol." <= ?",$minTime));
    }
	
	return $nbNounces;	
  }

  public function new_request_token($consumer){
  
    $token = Myzen_Oauth_Token::create('request',$consumer);
    echo $token->toString();  	
  }

  public function new_access_token($requestToken, $consumer) {
    $token = Myzen_Oauth_Token::create('access',$consumer,$requestToken);
    echo $token->toString();  	
  }

}